package com.cheyunkeji.er.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cheyun.netsalev3.MyApplication;
import com.cheyun.netsalev3.R;
import com.cheyun.netsalev3.utils.MySharedPreferences;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.app.GlobalConfig;
import com.cheyunkeji.er.app.UserInfoManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.UnAvailableChannelBean;
import com.cheyunkeji.er.bean.UserInfo;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.utils.AsciiCodeLimitFilter;
import com.cheyunkeji.er.utils.ChannelInfoUtil;
import com.cheyunkeji.er.utils.DensityUtil;
import com.cheyunkeji.er.utils.EncryptUtils;
import com.cheyunkeji.er.utils.PhoneUtil;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.umeng.analytics.MobclickAgent;


import java.io.File;
import java.util.HashMap;
import java.util.List;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;

public class LoginActivity extends BaseActivity {

  private static final String TAG = LoginActivity.class.getSimpleName();
  private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;

  @BindView(R.id.v_topbar)
  TopBar vTopbar;

  @BindView(R.id.et_phone_number)
  EditText etPhoneNumber;

  @BindView(R.id.et_psd)
  EditText etPsd;

  @BindView(R.id.tv_forget_psd)
  TextView tvForgetPsd;

  @BindView(R.id.btn_login)
  Button btnLogin;

  @BindView(R.id.activity_login)
  LinearLayout activityLogin;
  //    @BindView(R.id.call_login)
  //    ImageView call_login;
  @BindView(R.id.ll_register)
  TextView llRegister;

  @BindView(R.id.llys)
  LinearLayout llys;

  @Override
  protected void init() {
    setContentView(R.layout.er_activity_login);
    ButterKnife.bind(this);
    //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    //            getWindow().setStatusBarColor(Color.BLACK);

//    if (!MyApplication.getInstance().hasCheckVersion) {
//      new Handler()
//          .postDelayed(
//              new Runnable() {
//                @Override
//                public void run() {
//                  UpdatePresenter presenter = new UpdatePresenter(LoginActivity.this, 3);
//                  presenter.getVersionInfo();
//                  MyApplication.getInstance().hasCheckVersion = true;
//                }
//              },
//              1000);
//    }
  }

  @Override
  protected void initView() {

    if (!TextUtils.isEmpty(
        UserInfoManager.getInstance(MyApplication.getInstance().getApplicationContext())
            .getMobile())) {
      etPhoneNumber.setText(
          UserInfoManager.getInstance(MyApplication.getInstance().getApplicationContext())
              .getMobile());
    } else if (!TextUtils.isEmpty( MySharedPreferences.INSTANCE.getMobile())) {
      etPhoneNumber.setText(MySharedPreferences.INSTANCE.getMobile());
    }

    if (!TextUtils.isEmpty(
        UserInfoManager.getInstance(MyApplication.getInstance().getApplicationContext())
            .getPwd())) {
      etPsd.setText(
          UserInfoManager.getInstance(MyApplication.getInstance().getApplicationContext())
              .getPwd());
    }
    vTopbar.setTitle("登录");
    tvForgetPsd.setOnClickListener(this);
    btnLogin.setOnClickListener(this);
    //        call_login.setOnClickListener(this);
    llRegister.setOnClickListener(this);
    llys.setOnClickListener(this);
    //        密码框文字过滤器
    etPsd.setFilters(
        new InputFilter[] {
          new InputFilter.LengthFilter(Constants.PAD_LENGTH_RESTRICT), new AsciiCodeLimitFilter()
        });
  }

  @Override
  protected void initData() {}

  @Override
  public void onClick(View v) {
    super.onClick(v);

    Intent intent;
    switch (v.getId()) {
      case R.id.llys:
        {
          Dialog bottomDialog = new Dialog(v.getContext(), R.style.BottomDialog);
          View contentView =
              LayoutInflater.from(v.getContext()).inflate(R.layout.dialog_content_circle, null);
          bottomDialog.setContentView(contentView);
          ViewGroup.MarginLayoutParams params =
              (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
          params.width =
              v.getContext().getResources().getDisplayMetrics().widthPixels
                  - DensityUtil.dip2px(v.getContext(), 16f);
          params.bottomMargin = DensityUtil.dip2px(v.getContext(), 8f);
          contentView.setLayoutParams(params);
          bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
          bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
          bottomDialog.show();
          break;
        }
      case R.id.ll_register:
        intent = new Intent(this, RegisterOrFindPsdActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.ENTRY_ACTION_TYPE, Constants.ACTION_REGISTER);
        intent.putExtras(bundle);
        startActivity(intent);
        break;
        //            case R.id.ll_fast_experience:
        //                loginAction(Constants.FAST_EXPERIENCE_ACCOUNT,
        // Constants.FAST_EXPERIENCE_ACCOUNT_PSD);
        //                break;
      case R.id.btn_login:
        verifyInputLegality();
        break;

      case R.id.tv_forget_psd:
        intent = new Intent(this, RegisterOrFindPsdActivity.class);
        Bundle bundle2 = new Bundle();
        bundle2.putInt(Constants.ENTRY_ACTION_TYPE, Constants.ACTION_FIND_PSD_BACK);

        if (!TextUtils.isEmpty(etPhoneNumber.getText().toString())
            && PhoneUtil.isMobileNO(etPhoneNumber.getText().toString()))
          bundle2.putString("phone_number", etPhoneNumber.getText().toString());

        intent.putExtras(bundle2);
        startActivity(intent);

        break;
        //            case R.id.call_login:
        //                if (ContextCompat.checkSelfPermission(this,
        //                        Manifest.permission.CALL_PHONE)
        //                        != PackageManager.PERMISSION_GRANTED) {
        //
        //                    ActivityCompat.requestPermissions(this,
        //                            new String[]{Manifest.permission.CALL_PHONE},
        //                            MY_PERMISSIONS_REQUEST_CALL_PHONE);
        //                } else {
        //                    intent = new Intent(Intent.ACTION_CALL);
        //                    Uri data = Uri.parse("tel:" + "057187030075");
        //                    intent.setData(data);
        //                    startActivity(intent);
        //                }
        //                break;
      default:
        break;
    }
  }

  @Override
  public void onRequestPermissionsResult(
      int requestCode, String[] permissions, int[] grantResults) {

    switch (requestCode) {
      case MY_PERMISSIONS_REQUEST_CALL_PHONE:
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
          Intent intent = new Intent(Intent.ACTION_CALL);
          Uri data = Uri.parse("tel:" + "057187030075");
          intent.setData(data);
          if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
              != PackageManager.PERMISSION_GRANTED) {
            return;
          }
          startActivity(intent);
        } else {
          SToast.show("无法拨打电话");
        }

        break;

      default:
        break;
    }

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  }

  /** 账号密码合法性校验 */
  private void verifyInputLegality() {

    String phone = etPhoneNumber.getText().toString();
    String psd = etPsd.getText().toString();

    if (TextUtils.isEmpty(phone) || TextUtils.isEmpty(psd)) {
      showToast(R.string.input_error);
      etPhoneNumber.requestFocus();
      //            clearPhone();
      //            clearPsd();
      return;
    }

    if (!PhoneUtil.isMobileNO(phone)) {
      showToast(R.string.phone_number_error);
      //            clearPhone();
      //            clearPsd();
      return;
    }

    loginAction(phone, psd);
  }

  /**
   * 网络请求登录操作
   *
   * @param phone 账号
   * @param psd 密码
   */
  private void loginAction(final String phone, final String psd) {

    etPhoneNumber.clearFocus();
    etPhoneNumber.clearFocus();

    HashMap<String, String> params = new HashMap<>();
    params.put("user", phone);
    params.put("pass", EncryptUtils.encryptMD5ToString(psd));

    Log.e(TAG, "loginAction :  " + params.toString());

    ApiClient.postForm(
        HttpConstants.USER_LOGIN,
        params,
        new RespCallback<UserInfo>() {

          @Override
          protected void onSuccess(UserInfo data) {
            Log.e(TAG, "onSuccess ==========UserInfo============== : " + data.toString());
            //                etPsd.getText().clear();
            saveUserInfo(phone, psd, data);
            saveChannelInfo(data.getChannel_list(), data.getNo_list());
            startActivity(new Intent(LoginActivity.this, ChannelSelectActivity.class));
            //              友盟账号统计
            MobclickAgent.onProfileSignIn(phone);
          }

          @Override
          public void onError(Call call, Exception e, int id) {
            super.onError(call, e, id);
          }

          @Override
          public void onBefore(Request request, int id) {
            showDialog();
          }

          @Override
          public void onAfter(int id) {
            dismissDialog();
          }

          @Override
          protected void onRequestFailed(String msg) {
            SToast.show(msg);
          }
        });
  }

  /**
   * 反序列化通道信息到SharedPreference
   *
   * @param availableChannelList 从登录接口获取的通道数据集合
   */
  private void saveChannelInfo(
      List<UserInfo.ChannelListBean> availableChannelList,
      List<UnAvailableChannelBean> unAvailableChannelList) {

    if (availableChannelList != null) {
      ChannelInfoUtil.saveChannelInfoList(availableChannelList);
    }

    if (null != unAvailableChannelList) {
      ChannelInfoUtil.saveUnavailableChannelList(unAvailableChannelList);
    }
  }

  private void saveUserInfo(String phone, String psd, UserInfo data) {

    if (null != data) {
      //            sp存储用户关键信息
      UserInfoManager.getInstance(MyApplication.getInstance())
          .saveAccountAndPsd(phone, psd)
          .saveMid(data.getMid())
          .saveMobile(data.getMobile())
          .saveGender(data.getSex())
          .saveRealName(data.getRealname())
          .saveQQ(data.getQq())
          .saveAuthKey(data.getAuthkey());
      GlobalConfig.getInstance(getApplicationContext()).setLogined(true);
    }
  }

  public void clearPhone() {
    etPhoneNumber.getText().clear();
  }

  public void clearPsd() {
    etPsd.getText().clear();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    ApiClient.cancel(HttpConstants.USER_LOGIN);
  }

  private void openAPK(String fileSavePath) {
    File file = new File(Uri.parse(fileSavePath).getPath());
    String filePath = file.getAbsolutePath();
    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = null;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 判断版本大于等于7.0
      // 生成文件的uri，，
      // 注意 下面参数com.ausee.fileprovider 为apk的包名加上.fileprovider，
      data =
          FileProvider.getUriForFile(
              LoginActivity.this, "com.cheyunkeji.er.fileprovider", new File(filePath));
      intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 给目标应用一个临时授权
    } else {
      data = Uri.fromFile(file);
    }

    intent.setDataAndType(data, "application/vnd.android.package-archive");
    startActivity(intent);
  }
}
